<template>
  <base-layout>
    <div class="achievement-container">
      <!-- 新增成就卡片 -->
      <a-card class="add-achievement-card" title="新增成就">
        <div class="upload-section">
          <div class="upload-label">请上传证明文件：</div>
          <a-upload
            v-model:file-list="fileList"
            :before-upload="beforeUpload"
            :custom-request="handleCustomUpload"
            :max-count="1"
            @preview="handlePreview"
          >
            <a-button type="primary">
              <upload-outlined /> 上传文件
            </a-button>
          </a-upload>
          <div class="upload-tip">支持扩展名：pdf, jpg, png, img</div>
        </div>

        <div class="name-section">
          <div class="name-label">成就名称：</div>
          <a-input
            v-model:value="achievementName"
            placeholder="请输入成就名称"
            style="width: 100%"
          />
        </div>

        <div class="type-section">
          <div class="type-label">请选择成就类型：</div>
          <a-select
            v-model:value="achievementType"
            placeholder="请选择类型"
            style="width: 200px"
          >
            <a-select-option
              v-for="type in achievementTypes"
              :key="type.value"
              :value="type.value"
            >
              {{ type.label }}
            </a-select-option>
          </a-select>
        </div>

        <div class="subtype-section">
          <div class="subtype-label">子类型：</div>
          <a-select
            v-model:value="achievementSubType"
            placeholder="请选择子类型"
            style="width: 200px"
            :disabled="!achievementType"
          >
            <a-select-option
              v-for="subType in currentSubTypes"
              :key="subType.value"
              :value="subType.value"
            >
              {{ subType.label }}
            </a-select-option>
          </a-select>
        </div>

        <div class="third-type-section">
          <div class="third-type-label">具体类型：</div>
          <a-select
            v-model:value="achievementThirdType"
            placeholder="请选择具体类型"
            style="width: 200px"
            :disabled="!achievementSubType"
          >
            <a-select-option
              v-for="thirdType in currentThirdTypes"
              :key="thirdType.value"
              :value="thirdType.value"
            >
              {{ thirdType.label }}
            </a-select-option>
          </a-select>
        </div>

        <div class="description-section">
          <div class="description-label">成就说明：</div>
          <a-textarea
            v-model:value="description"
            placeholder="请填写说明"
            :auto-size="{ minRows: 4, maxRows: 6 }"
          />
        </div>

        <div class="submit-section">
          <a-button type="primary" @click="handleSubmit">提交</a-button>
        </div>
      </a-card>

      <!-- 成就列表卡片 -->
      <a-card class="achievement-list-card" title="我的成就列表">
        <a-table
          :columns="columns"
          :data-source="achievements"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a @click="handleDetail(record)">详情</a>
            </template>
            <template v-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'points'">
              <span :style="{ color: '#52c41a', fontWeight: 'bold' }">
                +{{ record.points }}
              </span>
            </template>
          </template>
        </a-table>
      </a-card>

      <!-- 预览模态框 -->
      <a-modal
        :visible="previewVisible"
        :title="previewTitle"
        :footer="null"
        @cancel="previewVisible = false"
      >
        <img :src="previewImage" style="width: 100%" />
      </a-modal>
    </div>
  </base-layout>
</template>

<script>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { 
  UploadOutlined,
  SearchOutlined
} from '@ant-design/icons-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import { achievementTypes } from '@/config/achievement'
import { 
  getAchievementList, 
  submitAchievement, 
  getAchievementDetail,
  getAchievementStats 
} from '@/api/achievement'

export default {
  name: 'Achievement',
  components: {
    BaseLayout,
    UploadOutlined,
    SearchOutlined
  },
  setup() {
    const fileList = ref([])
    const achievementName = ref('')
    const achievementType = ref('')
    const achievementSubType = ref('')
    const achievementThirdType = ref('')
    const description = ref('')
    const previewVisible = ref(false)
    const previewImage = ref('')
    const previewTitle = ref('')

    // 当前类型的子类型列表
    const currentSubTypes = computed(() => {
      const currentType = achievementTypes.find(type => type.value === achievementType.value)
      return currentType ? currentType.subTypes : []
    })

    // 当前子类型的第三级类型列表
    const currentThirdTypes = computed(() => {
      const currentType = achievementTypes.find(type => type.value === achievementType.value)
      if (!currentType) return []
      
      const currentSubType = currentType.subTypes.find(subType => subType.value === achievementSubType.value)
      return currentSubType ? currentSubType.thirdTypes : []
    })

    // 监听类型变化，重置子类型和第三级类型
    watch(achievementType, () => {
      achievementSubType.value = ''
      achievementThirdType.value = ''
    })

    // 监听子类型变化，重置第三级类型
    watch(achievementSubType, () => {
      achievementThirdType.value = ''
    })

    // 表格列定义
    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        key: 'id',
        width: 80
      },
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 100
      },
      {
        title: '子类型',
        dataIndex: 'subType',
        key: 'subType',
        width: 100
      },
      {
        title: '具体类型',
        dataIndex: 'thirdType',
        key: 'thirdType',
        width: 100
      },
      {
        title: '提交时间',
        dataIndex: 'submitTime',
        key: 'submitTime',
        width: 180
      },
      {
        title: '评审时间',
        dataIndex: 'reviewTime',
        key: 'reviewTime',
        width: 180
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100
      },
      {
        title: '积分',
        dataIndex: 'points',
        key: 'points',
        width: 100
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right'
      }
    ]

    // 统计数据
    const stats = ref({
      total: 25,
      approved: 18,
      pending: 7,
      points: 360
    })

    // 模拟数据
    const achievements = ref([
      {
        id: 1,
        name: 'CET-6 优秀成绩',
        type: '证书',
        subType: 'CET-6',
        thirdType: '550分以上',
        submitTime: '2024-03-15 14:30:00',
        reviewTime: '2024-03-16 09:15:00',
        status: 'reviewed',
        points: 20
      },
      {
        id: 2,
        name: '软件设计师证书',
        type: '证书',
        subType: '软考中级',
        thirdType: '软件设计师',
        submitTime: '2024-03-14 16:45:00',
        reviewTime: '-',
        status: 'pending',
        points: 0
      },
      {
        id: 3,
        name: '全国大学生创新创业大赛',
        type: '竞赛',
        subType: '国家级竞赛',
        thirdType: '创新创业',
        submitTime: '2024-03-10 11:20:00',
        reviewTime: '2024-03-12 14:30:00',
        status: 'reviewed',
        points: 50
      },
      {
        id: 4,
        name: '校园二手交易平台开发',
        type: '软著',
        subType: '应用软件',
        thirdType: '网站应用',
        submitTime: '2024-03-08 09:45:00',
        reviewTime: '2024-03-09 16:20:00',
        status: 'reviewed',
        points: 30
      }
    ])

    // 分页配置
    const pagination = reactive({
      total: 400,
      current: 1,
      pageSize: 10,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total) => `共 ${total} 条记录 第 ${pagination.current} / ${Math.ceil(total / pagination.pageSize)} 页`
    })

    // 处理文件上传前的验证
    const beforeUpload = (file) => {
      const isValidType = ['application/pdf', 'image/jpeg', 'image/png'].includes(file.type)
      if (!isValidType) {
        message.error('只能上传 PDF/JPG/PNG 格式的文件！')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        message.error('文件大小不能超过 10MB！')
        return false
      }
      return true
    }

    // 处理文件预览
    const handlePreview = async (file) => {
      if (!file.url && !file.preview) {
        if (file.originFileObj) {
          file.preview = await getBase64(file.originFileObj)
        }
      }

      // 如果是 PDF 文件，在新窗口打开
      if (file.type === 'application/pdf') {
        window.open(file.url || file.preview)
        return
      }

      // 图片文件使用模态框预览
      previewImage.value = file.url || file.preview
      previewVisible.value = true
      previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    }

    // 将文件转换为 Base64
    const getBase64 = (file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    }

    // 处理自定义上传
    const handleCustomUpload = ({ file, onSuccess, onError }) => {
      try {
        // 这里模拟上传，实际项目中需要调用上传接口
        getBase64(file).then(url => {
          const fileItem = {
            uid: Date.now(),
            name: file.name,
            status: 'done',
            url: url,
            type: file.type, // 添加文件类型信息
            originFileObj: file // 保存原始文件对象
          }
          fileList.value = [fileItem]
          onSuccess('上传成功')
          message.success('文件上传成功')
        })
      } catch (error) {
        onError(error)
        message.error('文件上传失败')
      }
    }

    // 获取统计数据
    const fetchStats = async () => {
      /* 注释掉 API 调用
      try {
        const res = await getAchievementStats()
        stats.value = res.data
      } catch (error) {
        message.error('获取统计数据失败')
      }
      */
    }

    // 获取成就列表
    const fetchAchievements = async () => {
      /* 注释掉 API 调用
      try {
        const res = await getAchievementList({
          page: pagination.current,
          pageSize: pagination.pageSize
        })
        achievements.value = res.data.list
        pagination.total = res.data.total
      } catch (error) {
        message.error('获取成就列表失败')
      }
      */
    }

    // 提交成就
    const handleSubmit = async () => {
      if (fileList.value.length === 0) {
        message.error('请上传证明文件')
        return
      }
      if (!achievementName.value.trim()) {
        message.error('请输入成就名称')
        return
      }
      if (!achievementType.value) {
        message.error('请选择成就类型')
        return
      }
      if (!achievementSubType.value) {
        message.error('请选择子类型')
        return
      }
      if (!achievementThirdType.value) {
        message.error('请选择具体类型')
        return
      }
      if (!description.value.trim()) {
        message.error('请填写说明')
        return
      }

      const formData = {
        name: achievementName.value,
        type: achievementType.value,
        subType: achievementSubType.value,
        thirdType: achievementThirdType.value,
        description: description.value,
        file: fileList.value[0]
      }

      /* 注释掉 API 调用
      try {
        await submitAchievement(formData)
        message.success('提交成功')
        // 重新获取列表和统计数据
        fetchAchievements()
        fetchStats()
      } catch (error) {
        message.error('提交失败')
        return
      }
      */

      message.success('提交成功')
      // 重置表单
      fileList.value = []
      achievementName.value = ''
      achievementType.value = ''
      achievementSubType.value = ''
      achievementThirdType.value = ''
      description.value = ''
    }

    // 处理表格分页变化
    const handleTableChange = (pag) => {
      pagination.current = pag.current
      // TODO: 调用获取数据接口
    }

    // 查看详情
    const handleDetail = async (record) => {
      /* 注释掉 API 调用
      try {
        const res = await getAchievementDetail(record.id)
        // TODO: 显示详情弹窗
        console.log(res.data)
      } catch (error) {
        message.error('获取详情失败')
      }
      */
      message.info(`查看成就详情：${record.id}`)
    }

    // 获取状态颜色
    const getStatusColor = (status) => {
      const colors = {
        pending: 'processing',
        reviewed: 'success',
        rejected: 'error'
      }
      return colors[status] || 'default'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const texts = {
        pending: '待审核',
        reviewed: '已通过',
        rejected: '已驳回'
      }
      return texts[status] || status
    }

    onMounted(() => {
      fetchAchievements()
    })

    return {
      fileList,
      achievementName,
      achievementType,
      achievementSubType,
      achievementThirdType,
      description,
      columns,
      achievements,
      pagination,
      beforeUpload,
      handleCustomUpload,
      handleSubmit,
      handleTableChange,
      handleDetail,
      getStatusColor,
      getStatusText,
      handlePreview,
      previewVisible,
      previewImage,
      previewTitle,
      achievementTypes,
      currentSubTypes,
      currentThirdTypes
    }
  }
}
</script>

<style scoped>
.achievement-container {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.add-achievement-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.upload-section {
  margin-bottom: 24px;
}

.upload-label {
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.85);
}

.upload-tip {
  margin-top: 8px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
}

.name-section {
  margin-bottom: 24px;
}

.name-label {
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.85);
}

.type-section {
  margin-bottom: 24px;
}

.type-label {
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.85);
}

.subtype-section {
  margin-bottom: 24px;
}

.subtype-label {
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.85);
}

.third-type-section {
  margin-bottom: 24px;
}

.third-type-label {
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.85);
}

.description-section {
  margin-bottom: 24px;
}

.description-label {
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.85);
}

.submit-section {
  text-align: right;
}

.achievement-list-card {
  border-radius: 8px;
}
</style> 